const express = require("express");
const router = express.Router();
const { Course, Category, User,Chapter } = require("../../models");
const { success, failure, NotFoundError } = require("../../utils/response");
/*
 * 接口1 - 查询课程列表（允许模糊查询,分页查询若不传参则默认显示第一页10条）
 * GET  /admin/courses?title=xxx
 * */
router.get("/", async function (req, res, next) {
  try {
    const query = req.query;
    // 当前是第几页，如果不传，那就是第一页(Math.abs是绝对值，Number是将字符串转换为数字)
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;

    // 进行排序(逆序)
    const condition = {
      attributes: { exclude: ["CategoryId", "UserId"] },
      include: [
        {
          model: Category,
          as: "category",
          attributes: ["id", "name"],
        },
        {
          model: User,
          as: "user",
          attributes: ["id", "username"],
        },
      ],
      order: [["id", "DESC"]],
      limit: pageSize, //文档要求使用limit和offset
      offset: (currentPage - 1) * pageSize, //计算出当前页的偏移量
    };
    if (query.categoryId) {
      condition.where = {
        categoryId: {
          [Op.eq]: `%${query.categoryId}%`,
        },
      };
    }
    if (query.userId) {
      condition.where = {
        userId: {
          [Op.eq]: `%${query.userId}%`,
        },
      };
    }

    if (query.name) {
      //.SQL语句中的like与%结合使用，可以模糊查询，%表示任意字符，%title%表示包含title的任意字符
      condition.where = { name: { [Op.like]: `%${query.categoryId}%` } };
    }

    if (query.recommended) {
      condition.where = {
        recommended: {
          // 需要转换为布尔值
          [Op.eq]: query.recommended === "true",
        },
      };
    }
    const { rows, count } = await Course.findAndCountAll(condition); //将findAll改为findAndCountAll，其返回的结果是一个对象，包含rows和count两个属性

    res.json({
      status: true,
      message: "查询课程列表成功。",
      data: {
        courses: rows, //课程列表
        pagination: {
          currentPage, //当前页码
          pageSize, //每页显示多少条数据
          total: count, //总条数
        },
      },
    });
  } catch (error) {
    // 如果发生错误，返回错误信息
    failure(res, error);
  }
});
// 查询课程详情
router.get("/:id", async function (req, res, next) {
  try {
    const condition = {
      attributes: { exclude: ["CategoryId", "UserId"] },
      include: [
        {
          model: Category,
          as: "category",
          attributes: ["id", "name"],
        },
        {
          model: User,
          as: "user",
          attributes: ["id", "username"],
        },
      ],
    };

    const course = await getCourse(req,condition);
    success(res, "查询课程详情成功", course);
  } catch (error) {
    failure(res, error);
  }
});

// 创建课程（POST）
router.post("/", async function (req, res, next) {
  try {
    // 使用白名单过滤
    const body = filterBody(req);
    // 获取当前用户ID
    body.userId = req.user.id;
    // Course.create方法会创建课程，并返回一个Promise对象
    const course = await Course.create(body);
    success(res, "创建课程成功", course, 201);
  } catch (error) {
    failure(res, error);
  }
});

// 更新课程（PUT）
router.put("/:id", async function (req, res, next) {
  try {
    const course = await getCourse(req);
    const body = filterBody(req);
    await course.update(body);
    success(res, "更新课程成功", course);
  } catch (error) {
    failure(res, error);
  }
});

// 删除课程（DELETE）
router.delete("/:id", async function (req, res, next) {
  try {
   const count = await Chapter.count({where:{courseId:req.params.id}})
   if(count>0){
    throw new NotFoundError(`ID:${req.params.id}课程下有章节，无法删除。`);
   }
    const course = await getCourse(req);
    // destroy方法会删除课程，并返回一个Promise对象
    await course.destroy();
    success(res, "删除课程成功");
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 公共方法：查询当前课程
 */
async function getCourse(req, condition = null) {
  let course;
  if (condition) {
    course = await Course.findByPk(req.params.id, condition);
  } else {
    course = await Course.findByPk(req.params.id);
  }

  if (!course) {
    throw new NotFoundError(`ID:${req.params.id}课程不存在。`);
  }
  return course;
}

/**
 * 白名单过滤（强参数过滤）去掉没有用到的参数
 * @param {*} req
 * @returns
 */
function filterBody(req) {
  return {
    categoryId: req.body.categoryId,
    // userId: req.body.userId,
    name: req.body.name,
    image: req.body.image,
    recommended: req.body.recommended,
    introductiory: req.body.introductiory,
    content: req.body.content,
    likesCount: req.body.likesCount,
    chaptersCount: req.body.chaptersCount,
  };
}

module.exports = router;
